﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BusinessObjects;
using DataObjects.EntityFramework.ModelMapper;
using System.Linq.Dynamic;

namespace DataObjects.EntityFramework.Implementation
{
    public class EntityServiceDao : IServiceDao
    {
        public Service GetService(int ServiceId)
        {
            using (var context = DataObjectFactory.CreateContext())
            {
                return Mapper.Map(context.ServiceEntities.FirstOrDefault(s => s.ServiceId == ServiceId));
            }
        }
        public List<Service> GetServices(string sortExpression = "ServiceId ASC")
        {
            using (var context = DataObjectFactory.CreateContext())
            {
                var list = new List<Service>();

                var services = context.ServiceEntities.AsQueryable().OrderBy(sortExpression).ToList();
                foreach (var service in services)
                    list.Add(Mapper.Map(service));

                return list;
            }
        }
        public void InsertService(Service service)
        {
            var entity = Mapper.Map(service);

            using (var context = DataObjectFactory.CreateContext())
            {
                context.ServiceEntities.AddObject(entity);
                context.SaveChanges();

                // update business object with new version and id
                service.ServiceId = entity.ServiceId;

                //country.Version = Convert.ToBase64String(entity.Version);
            }
        }
        public void UpdateService(Service service)
        {
            using (var context = DataObjectFactory.CreateContext())
            {
                var entity = context.ServiceEntities.Where(p => p.ServiceId == service.ServiceId).SingleOrDefault();

                entity.ServiceId = service.ServiceId;
                entity.Description = service.Description;

                context.ServiceEntities.ApplyCurrentValues(entity);
                context.SaveChanges();

                // Update business object with new version
                //country.Version = Convert.ToBase64String(entity.Version);
            }
        }
        public void DeleteService(Service service)
        {
            using (var context = DataObjectFactory.CreateContext())
            {
                var entity = context.ServiceEntities.Where(s => s.ServiceId == service.ServiceId).SingleOrDefault();
                context.ServiceEntities.DeleteObject(entity);
                context.SaveChanges();
            }
        }
    }
}
